package com.test.testcrash;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.iflytek.crashcollect.CrashCollector;
import com.iflytek.crashcollect.baseinfocollect.HeartbeatInfo;
import com.iflytek.crashcollect.collectcontrol.CrashInfo;
import com.iflytek.crashcollect.crashupload.CrashUpLoadRequest;
import com.iflytek.crashcollect.crashupload.UploadListener;
import com.iflytek.crashcollect.dump.DumpEntity;
import com.iflytek.crashcollect.notifier.CrashNotifier;
import com.iflytek.crashcollect.userstrategy.UploadType;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {
    private static final String TAG = "crashcollect_MainActivity";

    private Button btnInit;
    private Button btnJavaCrash;
    private Button btnNativeCrash;
    private Button btnMakeAnr;

    private Button btnPostException;
    private Button btnOutOfMemory;

    private Button btnTriggerUpload;

    private Button btnProcess1Crash;
    private Button btnProcess2Crash;

    private Button btnReceiverAnr;
    private Button btnServiceAnr;

    private Button btnMakeNilCrash;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnInit = (Button) findViewById(R.id.btn_init);
        btnInit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initCrashCollector();
            }
        });

        btnJavaCrash = (Button) findViewById(R.id.btn_java_crash);
        btnJavaCrash.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                makeJavaCrash();
            }
        });

        btnNativeCrash = (Button) findViewById(R.id.btn_native_crash);
        btnNativeCrash.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                makeNativeCrash();
            }
        });

        btnMakeAnr = (Button) findViewById(R.id.btn_make_anr);
        btnMakeAnr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                makeAnr();
            }
        });

        btnPostException = (Button) findViewById(R.id.btn_post_catch_exception);
        btnPostException.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                postException();
            }
        });

        btnOutOfMemory = (Button) findViewById(R.id.btn_out_of_memory);
        btnOutOfMemory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                makeOom();
            }
        });

        btnTriggerUpload = (Button) findViewById(R.id.btn_trigger_upload);
        btnTriggerUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                triggerUpload();
            }
        });

        btnProcess1Crash = (Button) findViewById(R.id.btn_process1_crash);
        btnProcess1Crash.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                makeProcess1Crash();
            }
        });

        btnProcess2Crash = (Button) findViewById(R.id.btn_process2_crash);
        btnProcess2Crash.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                makeProcess2Crash();
            }
        });

        btnReceiverAnr = (Button) findViewById(R.id.btn_make_anr_receiver);
        btnReceiverAnr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                makeReceiverANR();
            }
        });

        btnServiceAnr = (Button) findViewById(R.id.btn_make_anr_service);
        btnServiceAnr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                makeServiceANR();
            }
        });

        btnMakeNilCrash = (Button) findViewById(R.id.btn_make_nil_crash);
        btnMakeNilCrash.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                makeNullPointException();
            }
        });

        //initCrashCollector();
    }

    /**
     * 模拟service发送anr
     */
    private void makeServiceANR() {
        Intent intent = new Intent(this, MyService.class);
        //intent.putExtra("crash", "makeProcess1Crash");
        intent.putExtra("method", "makeanr");
        startService(intent);
    }

    /**
     * 模拟广播发送anr
     */
    private void makeReceiverANR() {
        Intent intent = new Intent("com.iflytek.crashcollect.demo.makeanr");
        sendBroadcast(intent);
    }

    /**
     * 模拟anr
     */
    public void makeAnr() {
        btnMakeAnr.setText("make anr start");
        for (int i = 0; i < 30; ++i) {
            try {
                Thread.sleep(1000 * 5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        btnMakeAnr.setText("make anr finish");
    }

    /**
     * 初始化崩溃收集
     */
    public void initCrashCollector() {
        //日志开关， true打开，false:关闭
        CrashCollector.setDebugable(true);

        //初始化崩溃sdk
        CrashCollector.init(getApplicationContext(), "100IME", new CrashUpLoadRequest() {
            @Override
            public void uploadCrash(List<CrashInfo> list, UploadListener uploadListener) {
                //此处上传崩溃堆栈

                for (CrashInfo crashInfo : list) {
                    Log.d(TAG, "uploadCrash | json = " + crashInfo.toJson());
                }

                uploadListener.onUploadSuccess();
            }

            @Override
            public void uploadDump(List<DumpEntity> list, UploadListener uploadListener) {
                //此处需要上传OOM的内存dump文件,可以不上传
            }

            @Override
            public void uploadLog(List<HeartbeatInfo> list, UploadListener uploadListener) {
                //此处需要上传心跳,平均1h/次,方便后台按小时统计活跃,可以不上传
            }
        });

        //设置uid
        CrashCollector.setUid("140527194034951125");

        //设置渠道号
        CrashCollector.setChannelId("01010000");

        //设置wifi下上传全量信息
        CrashCollector.setUploadTypeByMobile(UploadType.UPLOAD_FULL);

        //设置在移动网络下上传精简的崩溃信息
        CrashCollector.setUploadTypeByWifi(UploadType.UPLOAD_LITE);

        if (BuildConfig.DEBUG) {
            //崩溃信息的通知栏提示，方便测试查看问题（release版本，不要开启）
            CrashNotifier.start(getApplicationContext());
        }
        com.iflytek.xorm.util.Logger.setDebugable(true);
    }

    /**
     * 获取当前进程名
     */
    public static String getCurrentProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager mActivityManager = (ActivityManager) context.getSystemService(
                Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    public void makeJavaCrash() {
        Integer[] a = new Integer[0];
        a[0] = 1;
        a[1] = 2;
    }

    public void makeNativeCrash() {
        TestJni.makeCrash();
    }

    public void postException() {
        ArrayList<String> list = new ArrayList<String>();
        list.add("hello");
        list.add("world");

        try {
            for (String str : list) {
                list.remove(str);
            }
        } catch (Exception e) {
            CrashCollector.postCatchedException(e);
        }
    }

    /**
     * 生成一个oom的异常，需要在/sdcard/iFlyIME/crash/目录下放一张test.jpg的图片
     */
    private void makeOom() {
        String filename = "/sdcard/iFlyIME/crash/test.jpg";
        List<Bitmap> list = new ArrayList<>();
        for (int i = 0; i < 1000; ++i) {
            Log.d(TAG, "makeOom | load image" + i);
            Bitmap bitmap = BitmapFactory.decodeFile(filename);
            list.add(bitmap);
        }
    }

    private void triggerUpload() {
        CrashCollector.triggerUpload();
    }

    /**
     * 模拟主进程崩溃
     */
    private void makeProcess1Crash() {
        Intent intent = new Intent(this, MyService.class);
        intent.putExtra("crash", "makeProcess1Crash");
        startService(intent);
    }

    /**
     * 模拟process2崩溃
     */
    private void makeProcess2Crash() {
        Intent intent = new Intent(this, MyService2.class);
        intent.putExtra("crash", "makeProcess2Crash");
        startService(intent);
    }

    /**
     * 模拟空指针崩溃
     */
    private void makeNullPointException() {
        String str = null;
        int idx = str.indexOf("iflytek");
    }
}
